package com.axend.lib_base.utils

import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import java.lang.ref.WeakReference

object UsbUtils {

    private lateinit var context: WeakReference<Context>
    private lateinit var usbManager: UsbManager

    fun init(context: Context) {
        UsbUtils.context = WeakReference<Context>(context)
        context?.let {
            this.usbManager = it.getSystemService(Context.USB_SERVICE) as UsbManager
        }
    }

    /**
     * 检查是否有指定VID和PID的USB设备连接
     */
    fun isDeviceConnected(vid: Int, pid: Int): Boolean {
        val deviceList = usbManager.deviceList
        return deviceList.values.any { it.vendorId == vid && it.productId == pid }
    }

    /**
     * 获取指定VID和PID的USB设备
     */
    fun getDeviceByVidPid(vid: Int, pid: Int): UsbDevice? {
        return usbManager.deviceList.values.find { it.vendorId == vid && it.productId == pid }
    }

    /**
     * 请求USB设备权限
     */
    fun requestPermission(device: UsbDevice, permissionIntent: PendingIntent) {
        context.get()?.registerReceiver(PermissionReceiver(), IntentFilter("usb"))
        usbManager.requestPermission(device, permissionIntent)
    }

    /**
     * 权限请求结果广播接收器
     */
    private class PermissionReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent?.action == "usb") {
                val device = intent?.getParcelableExtra<UsbDevice>(UsbManager.EXTRA_DEVICE)
                if (intent!!.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                    // 权限被授予，可以进行后续操作
                    // ...
                } else {
                    // 权限被拒绝
                    // ...
                }
            }
        }
    }
}
